﻿using Microsoft.AspNetCore.Mvc;
using RuoVea.ExDto;
using RuoVea.ExEnum;
using RuoVea.ExUtil;
using RuoVea.Tool.Entity;
using SqlSugar;

namespace RuoVea.Tool.Controllers
{
    public class AirController : Controller
    {
        private readonly ISqlSugarClient _repository;

        public AirController(ISqlSugarClient sqlSugarClient)
        {
            _repository = sqlSugarClient;
        }
        public IActionResult Index(string code)
        {
            if (code.NotNullOrWhiteSpace())
            {
                ViewBag.data = _repository.Queryable<TextAirEntity>().Where(x => x.Code == code && x.CreatedTime > DateTime.Now.AddDays(-7)).Select(x => x.Content).First();
            }

            return View();
        }

        public IActionResult Send(string content)
        {
            if (content.Trim().IsNullOrWhiteSpace())
                return Fail("内容不能为空");
            var code = RuoVea.ExUtil.Common.Common.RndNum(6);
            TextAirEntity textAir = new TextAirEntity
            {
                Code = code,
                Content = content,
                CreatedTime = DateTime.Now,
                Ip =  this.HttpContext?.Connection?.LocalIpAddress?.MapToIPv4()?.ToString()
            };
            try { textAir.Ip= this.Request.Headers["X-Forwarded-For"].FirstOrDefault(); } catch { }
            var res = _repository.Insertable<TextAirEntity>(textAir).ExecuteCommand();
            if (res > 0)
                return Success(code);
            else return Fail("内容发件失败");
        }

        public IActionResult Accept(string code)
        {
            if (code.IsNullOrWhiteSpace())
                return Fail("取件码不能为空");
            var data = _repository.Queryable<TextAirEntity>().Where(x => x.Code == code && x.CreatedTime > DateTime.Now.AddDays(-7)).Select(x => x.Content).First();
            if (data.IsNullOrWhiteSpace())
                return Fail("该消息不存在");
            else return Success(data);
        }

        #region 返回消息
        /// <summary>
        /// 返回失败消息
        /// </summary>
        /// <param name="info">消息</param>
        /// <returns></returns>
        protected virtual ActionResult Fail(string info)
        {
            return Content(new RestfulResult { Code = HttpStatusCode.BadRequest, Message = info }.Json2Str());
        }

        /// <summary>
        /// 返回成功数据
        /// </summary>
        /// <param name="data">数据</param>
        /// <returns></returns>
        protected virtual ActionResult Success(object data)
        {
            return Content(new RestfulResult { Code = HttpStatusCode.OK, Message = "响应成功", Data = data }.Json2Str());
        }
        #endregion
    }
}
